from flask import Flask, url_for, render_template,request
from forms import LoginForm
from flask_sqlalchemy import SQLAlchemy
import pymysql
from flask_migrate import Migrate,MigrateCommand
from flask_script import Manager,Command
from collections import namedtuple


app = Flask(__name__)
app.config['SECRET_KEY'] = 'daxiongketang'
# sqlalchemy配置
app.config['SQLALCHEMY_DATABASE_URI'] = (
    'mysql+pymysql://root:andy123456@localhost/flask_demo?charset=utf8mb4'
)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 调试模式，可以动态加载代码
app.debug = True

db = SQLAlchemy(app)
migrate = Migrate(app,db)

manager = Manager(app)

# 继承command类
class Hello(Command):
    def run(self):
        print('hello world')


manager.add_command('hello',Hello())
manager.add_command('db',MigrateCommand)

# 装饰器方式添加命令
# @manager.command
# def hi():
#     print('hi,andy')

@manager.option('-n','--name',help='填写name')
def hi(name):
    print(f'hi ,{name}')

# 测试类
class User(db.Model):
    __tablename__ = 'user'

    id = db.Column(db.Integer,autoincrement=True,primary_key=True)
    username = db.Column(db.String(80),unique=True,nullable=False)
    gender = db.Column(db.Boolean,default=True)
    hobby = db.Column(db.String(120))
    email = db.Column(db.String(120),unique=True,nullable=False)
    password = db.Column(db.String(20),nullable=False)
    articles = db.relationship('Article',backref='user')

    def __repr__(self):
        return f"<User> is {self.username}"


class Article(db.Model):
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    title = db.Column(db.String(80),unique=True,nullable=False)
    content = db.Column(db.Text)
    user_id = db.Column(db.Integer,db.ForeignKey('user.id'))

    def __repr__(self):
        return f"<Article> is {self.title}"


# 表单的测试
# 测试登陆方法
@app.route('/login/',methods=['GET','POST'])
def login():
    form = LoginForm(request.form)
    # if request.method == 'POST' and form.validate():
    if form.validate_on_submit():
        # 登录流程
        pass

    return render_template('login.html',form=form)

# 传递参数方式二：较为复杂的参数
@app.route('/')
def index():
    dict_val = {'name':'andy','age':18}
    list_val = [i for i in range(10)]
    User = namedtuple('User','name age')
    user = User('daxiong',18)
    return render_template('index.html',info=dict_val,number=list_val,user=user)


# 传参方式一： web端页面传递参数（单一参数）
@app.route('/user/<username>')
def show_user_info(username):
    return render_template('user.html', name=username)

# 接受int类型的入参
@app.route('/post/<int:post_id>')
def show_post_info(post_id):
    return f'post_id是{post_id}'

# 测试---链接跳转
@app.route('/test/')
def test():
    return url_for('show_user_info', username='andy')


if __name__ == "__main__":
    # app.run(
    #     debug=True,
    #     port=8000
    # )
    # db.create_all()
    manager.run()